<template>
  <el-row>
    <el-col :span="24">
      <vxe-toolbar setting>
        <template v-slot:buttons>
          <el-button @click="saveGroup">保存</el-button>
        </template>
      </vxe-toolbar>
      <vxe-table ref="xTable" class="vxe-table-element" border auto-resize show-overflow :loading="loading" :data.sync="tableData">
        <vxe-table-column type="selection" width="50"></vxe-table-column>
        <vxe-table-column type="index" width="50"></vxe-table-column>
        <vxe-table-column field="groupId" title="ID"></vxe-table-column>
        <vxe-table-column field="groupName" title="名称"></vxe-table-column>
      </vxe-table>
    </el-col>
  </el-row>
</template>
<script>
import { mapState, mapActions, mapGetters } from "vuex";
import Message from "../../common/Message";
export default {
  data() {
    return {
      loading: false,
      tableData: []
    };
  },
  computed: {
    ...mapGetters("http", ["userGroups"])
  },
  watch: {
    userGroups: {
      deep: true,
      handler(val, oldVal) {
        this.loadGroupsTable();
      }
    }
  },
  methods: {
    ...mapActions("http", ["loadUserGroups", "getUserGroups"]),
    ...mapActions(["addSelectedUserGroups"]),
    loadGroupsTable() {
      let userGroups = this.$store.state.http.userGroups;
      let tableData = [];
      userGroups.forEach(e => {
        let group = { groupId: e.id, groupName: e.name };
        tableData.push(group);
      });
      this.tableData = tableData;
    },
    saveGroup() {
      let records = this.$refs.xTable.getSelectRecords();
      this.addSelectedUserGroups(records);
      this.$emit("close");
    },
    getGroupList() {
      this.loading = true;
      this.getUserGroups()
        .then(response => {
          console.log("获取用户组成功", response);
          let list = response.data.groups;
          this.loadUserGroups(list);
          this.loading = false;
        })
        .catch(error => {
          console.error("获取用户组异常", error);
          this.loading = false;
        });
    }
  },
  mounted() {
    this.getGroupList();
  }
};
</script>
